package com.byxy.ssm.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.byxy.ssm.demo.entity.Items;
import com.byxy.ssm.demo.service.ItemsService;

@Controller
@RequestMapping("items")
public class ItemsController {
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "add";
	}

	@Autowired
	private ItemsService itemsService;
	@PostMapping("add") 
	// @RequestMapping(value = "add", method = RequestMethod.POST)
	public String add2(Items item, MultipartFile imgFile,HttpServletRequest req) throws Exception, IOException {
		String path = req.getSession().getServletContext().getRealPath("images");
		imgFile.transferTo(new File(path,imgFile.getOriginalFilename()));
		item.setImg("images/" + imgFile.getOriginalFilename());
		itemsService.save(item);
		return "redirect:list";
	}
	//第一种写法
	@GetMapping("list")
	public String list(Model model) {
		List<Items> items = itemsService.findAll();
		model.addAttribute("list", items);
		return "list";
	}
	// 第二种写法
	@RequestMapping(value = "list2", method = RequestMethod.GET)
	public ModelAndView list2() {
		ModelAndView mv = new ModelAndView();
		List<Items> items = itemsService.findAll();
		mv.addObject("list", items);
		mv.setViewName("list");
		return mv;
	}
	// 通过session传值  Servlet知识   (HttpSession session)
	@GetMapping("list3")
	public String list3(HttpSession session) {
		List<Items> items = itemsService.findAll();
		session.setAttribute("list3", items);
		return "list";
	}
	/**
	 * 返回json
	 * @return
	 */
	//必须出现价格
	@ResponseBody
	@GetMapping("listjson")
	public List<Items> listjson() {
		return itemsService.findAll();
	}
	// 不能出现价格
	@ResponseBody
	@GetMapping("listjson2")
	public List<Items> listjson2() {
		return itemsService.findAll();
	}
}
